package com.chlvip.demo.redisson.controller;

import lombok.Data;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.redisson.spring.transaction.RedissonTransactionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.annotation.SessionScope;

@RestController
public class TestController {

    @Autowired
    private TestData testData;
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private RedissonTransactionManager transactionManager;

    @RequestMapping("test")
    @Cacheable("test")
    public String test() {
        System.out.println("执行test方法");
        return "ok";
    }

    @RequestMapping("put")
    @Transactional(value = "redissonTransactionManager")
    public String put() {
        //使用事务例子
        RMap<Object, Object> rmap = transactionManager.getCurrentTransaction().getMap("testMap");
        long time = System.currentTimeMillis();
        rmap.put("test", time);
        System.out.println("put" + time);
        testData.setNumber(5);
        return "put" + time;
    }

    @RequestMapping("get")
    public String get() {
        RMap<Object, Object> testMap = redissonClient.getMap("testMap");
        return "get" + testMap.get("test");
    }

    /**
     * 测试数据类型
     */
    @Data
    @Component
    @SessionScope
    public static class TestData {
        private Number number;
    }
}
